local addonName, IWonew = ...

PetToolClass = {}
PetToolClass.__index = PetToolClass

function PetToolClass:new()
  local instance = setmetatable({}, PetToolClass)
	return instance
end

function PetToolClass:PackagePets()
  local packList = {"生气勃勃的天驹","符光跳跃者","致命的骨牙猪","噬食心蛛","饥饿的潜地者", "翼狮幼崽", "岩肤惊惧之翼宝宝", "小灵通"}

  local numPets, numOwned = C_PetJournal.GetNumPets()

  for i = 1, numOwned do
      local petID, speciesID, owned, customName, level, favorite, isRevoked, speciesName, icon, petType, companionID, tooltip, description, isWild, canBattle, isTradeable, isUnique, obtainable = C_PetJournal.GetPetInfoByIndex(i)
      if petID and IWonew.contains(packList, speciesName) then
          C_PetJournal.CagePetByID(petID)
      end
  end
end

function PetToolClass:CheckMissionState()
  local currentRole, currentRealm = UnitFullName("player")
  -- 获取心能
  local userAnimaQuantity = C_CurrencyInfo.GetCurrencyInfo(C_CovenantSanctumUI.GetAnimaInfo()).quantity
  local bagAnimaQuantity = self:GetBagAnimaQuantity()
  local petCharmCount = self:GetUserBagItemCount(163036)
  local jiangrenzhiminCount = self:GetUserBagItemCount(210814)
  local userConcentration = self:GetConcentration()
  -- 战役等级
  local missionLevel = C_CurrencyInfo.GetCurrencyInfo(1889).quantity
  -- 盟约等级
  local renownLevel = C_CurrencyInfo.GetCurrencyInfo(1822).quantity
  -- 追随者数量
  local followers = C_Garrison.GetFollowers(123)
  local followersFullCount = #followers
  local followersCount = 0
  for i = 1, followersFullCount do
    if followers[i].isCollected then
      followersCount = followersCount + 1
    end
  end
  local newPetMissions = self:GetNewPetMissions()
  local newPetMissionsResult = ""
  for i = 1, #newPetMissions do
    local mission = newPetMissions[i]
    local split = ""
    if i > 1 then
      split = "|"
    end
    newPetMissionsResult = newPetMissionsResult .. split .. "ID_" .. mission.missionID .. "#quantity_" .. mission.quantity .. "#duration_" .. mission.duration
  end
  local awardQuestState = self:GetAwardQuestState(61984)
  local chuQuestState = self:GetAwardQuestState(65763)
  local factionState = self:GetFactionState()
  local posState = self:GetPosState()
  local speedState = self:GetSpeed()
  local resultSet = {
    role=currentRole,
    realm=currentRealm,
    itemID_Pet_1 = userAnimaQuantity,
    itemID_Pet_2 = bagAnimaQuantity,
    itemID_Pet_3 = petCharmCount,
    itemID_Pet_4 = missionLevel,
    itemID_Pet_5 = renownLevel,
    itemID_Pet_6 = followersCount,
    itemID_Pet_7 = newPetMissionsResult,
    itemID_Pet_8 = awardQuestState,
    itemID_Pet_9 = factionState.result,
    itemID_Pet_10 = posState,
    itemID_Pet_11 = speedState,
    itemID_Pet_12 = jiangrenzhiminCount,
    itemID_Pet_13 = userConcentration,
  }
  local parts = {}
  for key, value in pairs(resultSet) do
    table.insert(parts, key .. "=" .. tostring(value))
  end
  local output = table.concat(parts, "&")

  
  -- local resultString = "userAnimaQuantity:" .. tostring(userAnimaQuantity)
  -- .. "&" .. "bagAnimaQuantity:" .. tostring(bagAnimaQuantity)
  -- .. "&" .. "petCharmCount:" .. tostring(petCharmCount)
  -- .. "&" .. "missionLevel:" .. tostring(missionLevel)
  -- .. "&" .. "renownLevel:" .. tostring(renownLevel)
  -- .. "&" .. "followersCount:" .. tostring(followersCount)
  -- .. "&" .. "followersFullCount:" .. tostring(followersFullCount)
  --  .. "&" .. "newPetMissions:" .. #newPetMissions
  --  print(resultString)
  IWonew.Log("MISSION_PET_STATE----" .. "{" .. output .. "}")
end

function PetToolClass:GetConcentration()
  local dz_skillLineID = 2872 -- 锻造skillLineID
  local dz_currencyType = C_TradeSkillUI.GetConcentrationCurrencyID(dz_skillLineID)
  local dz_currencyInfo = C_CurrencyInfo.GetCurrencyInfo(dz_currencyType)

  local fm_skillLineID = 2874 -- 附魔skillLineID
  local fm_currencyType = C_TradeSkillUI.GetConcentrationCurrencyID(fm_skillLineID)
  local fm_currencyInfo = C_CurrencyInfo.GetCurrencyInfo(fm_currencyType)
  return 'dz=' .. tostring(dz_currencyInfo.quantity) .. "|fm=" .. tostring(fm_currencyInfo.quantity)
end

function PetToolClass:GetPosState()
  local map = C_Map.GetBestMapForUnit("player")
  if not map then 
    return ""
  end
  local position = C_Map.GetPlayerMapPosition(map, "player")
  if not position then 
    return ""
  end
  local facing = GetPlayerFacing()
  local x, y = position:GetXY()
  return tostring(x) .. "|" .. tostring(y) .. "|" ..tostring(facing)
end

function PetToolClass:GetSpeed()
  local currentSpeed, walkSpeed, runSpeed = GetUnitSpeed("player")
  return tostring(walkSpeed) .. "|" .. tostring(runSpeed)
end

function PetToolClass:GetFactionState()
  local factionList = {
    {id = 2410, name = "不朽军团"},
    {id = 2465, name = "荒猎团"},
    {id = 2472, name = "开悟者"},
    {id = 2407, name = "晋升者"},
    {id = 2413, name = "收割者之庭"},
  }
  local infoList = {}
  local resultTbl = {}
  for i = 1, #factionList do
    local currentValue, threshold, rewardQuestID, hasRewardPending, tooLowLevelForParagon = C_Reputation.GetFactionParagonInfo(factionList[i].id)
    -- print(factionList[i].name, currentValue, threshold, rewardQuestID, hasRewardPending, tooLowLevelForParagon)
    if currentValue then
      table.insert(infoList, {id = factionList[i].id, name = factionList[i].name, currentValue=currentValue, threshold=threshold, rewardQuestID=rewardQuestID, hasRewardPending=hasRewardPending, tooLowLevelForParagon=tooLowLevelForParagon})
      local singTbl = {"name_" .. factionList[i].name, "hasRewardPending_" .. (hasRewardPending and 1 or 0)}
      table.insert(resultTbl, table.concat(singTbl, "#"))
    end
  end
  return {info=infoList, result=table.concat(resultTbl, "|")}
end

function PetToolClass:GetAwardQuestState(questID)
  local isComplete = C_QuestLog.IsComplete(questID)
  local isAccept = C_QuestLog.IsOnQuest(questID)
  local isAwarded = C_QuestLog.IsQuestFlaggedCompleted(questID)
  -- 已交任务
  if isAwarded then return 1 end
  -- 未接任务
  if not isAccept then return 2 end
  -- 未完成
  if not isComplete then 
    local objectives = C_QuestLog.GetQuestObjectives(questID)
    local text = ""
    if objectives then
        for i,objective in ipairs(objectives) do
          text = text .. objective.text
        end
    end
    return '3_' ..  text
  end
  -- 已完成
  return 4
end

function PetToolClass:GetUserBagItemCount(itemID)
  local items = IWonew.GetAllBagItems()
  local count = 0
  for i = 1, #items do
    if items[i].itemID == itemID then
      count = items[i].stackCount
    end
  end
  return count
end

function PetToolClass:GetNewPetMissions()
  local missions = C_Garrison.GetAvailableMissions(123)
  -- local missions = C_Garrison.GetInProgressMissions(123)
  local petMissions = {}
  for _, mission in pairs(missions) do
    local rewards = mission.rewards
    for _, reward in pairs(rewards) do
      if reward.itemID == 163036 then
        table.insert(petMissions, {missionID=mission.missionID, quantity=reward.quantity, name=mission.name, duration=mission.duration})
      end
    end
  end
  return petMissions
end

function PetToolClass:GetBagAnimaQuantity()
  local items = IWonew.GetAllBagItems()
  local numSet = {0}
  for i = 1, #items do
    local tooltip = C_TooltipInfo.GetBagItem(items[i].bagID, items[i].slotID)
    if tooltip and tooltip.lines then
    for _, line in ipairs(tooltip.lines) do
      if line.leftText and line.leftText:find("份心能") then
        local num = string.match(line.leftText, "(%d+)")
        if num then
          table.insert(numSet, tonumber(num) * items[i].stackCount)
        end
        break  -- 找到就跳出
      end
    end
  end
  end
  local sum = 0
  for _, v in ipairs(numSet) do
    sum = sum + v
  end
  return sum
end

function PetToolClass:CompleteFactionQuest()
  local info = C_GossipInfo.GetActiveQuests()
  local questID = nil
  for i = 1, #info do
    questID = info[i].questID
  end
  if questID then
    C_GossipInfo.SelectActiveQuest(questID)
  end
  CompleteQuest()
  GetQuestReward()
end

local PetTool_instance = nil
function CreatePetToolInstance()
  if PetTool_instance == nil then
    PetTool_instance = PetToolClass:new()
  end
  return PetTool_instance
end


function PackagePets()
    CreatePetToolInstance():PackagePets()
    -- print(ids)
end
-- /dump PetTool_CheckMissionState()
function PetTool_CheckMissionState()
  CreatePetToolInstance():CheckMissionState()
  -- print(CreatePetToolInstance():GetAwardQuestState(61984))
end

function PetTool_CompleteFactionQuest()
  CreatePetToolInstance():CompleteFactionQuest()
end
-- /dump PetTool_MoveTest()
function PetTool_MoveTest()
  local questID = 61984 -- 替换为你的任务ID
  local objectives = C_QuestLog.GetQuestObjectives(questID)
  if objectives then
      for i,objective in ipairs(objectives) do
          print("目标"..i..":", objective.text, objective.finished and "(完成)" or "(未完成)")
      end
  end
  
end
-- /dump PetTool_Debug()
function PetTool_Debug()
  -- CreatePetToolInstance():GetPosState()
  -- print(CreatePetToolInstance():GetAwardQuestState(61984))
  print(1)
--   /run C_GossipInfo.SelectAvailableQuest(任务ID)
-- /run CompleteQuest()
-- /run GetQuestReward()
  -- /run C_GossipInfo.SelectActiveQuest(61098)
  -- /run CompleteQuest()
  -- /run GetQuestReward()
  local info = C_GossipInfo.GetActiveQuests()
  local questID = nil
  for i = 1, #info do
    print(info[i].title, info[i].questID)
  end
  -- local dd = GetNumQuestLogEntries()
  -- print(IWonew.TableToString(dd))
  print(2)
end